// 定位封装对象,检测定位服务是否打开
// 打开系统设置，应用权限
const handleLocation = {
  // 安卓获取打开系统定位权限
  android: function() {
    var context = plus.android.importClass('android.content.Context')
    var locationManager = plus.android.importClass('android.location.LocationManager')
    var main = plus.android.runtimeMainActivity()
    var mainSvr = main.getSystemService(context.LOCATION_SERVICE)
    if (!mainSvr.isProviderEnabled(locationManager.GPS_PROVIDER)) {
      uni.showModal({
        title: '提示',
        content: '请打开定位权限, 为您提供更丰富的本地服务功能',
        showCancel: true,
        success: res => {
          if (res.confirm) {
            if (!mainSvr.isProviderEnabled(locationManager.GPS_PROVIDER)) {
              var Intent = plus.android.importClass('android.content.Intent')
              var Settings = plus.android.importClass('android.provider.Settings')
              var intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
              main.startActivity(intent) // 打开系统设置GPS服务页面
            } else {
              console.log('GPS功能已开启')
            }
          }

        }
      })
    }
  },
  // ios获取打开系统定位权限
  ios: function() {
    var cllocationManger = plus.ios.import('CLLocationManager')
    var enable = cllocationManger.locationServicesEnabled()
    var status = cllocationManger.authorizationStatus()
    if (enable && status !== 2) {
      console.log('手机系统的定位已经打开')
    } else {
      uni.showModal({
        title: '提示',
        content: '请打开定位权限, 为您提供更丰富的本地服务功能',
        showCancel: true,
        success: res => {
          if (res.confirm) {
            var UIApplication = plus.ios.importClass('UIApplication')
            var application2 = UIApplication.sharedApplication()
            var NSURL2 = plus.ios.importClass('NSURL')
            var setting2 = NSURL2.URLWithString('app-settings:') // 打开应用权限
            application2.openURL(setting2)
            plus.ios.deleteObject(setting2)
            plus.ios.deleteObject(NSURL2)
            plus.ios.deleteObject(application2)
          }
        },
        fail: err => {
          console.log('打开定位功能失败')
        }
      })
    }
    plus.ios.deleteObject(cllocationManger)
  }
}

// 判断是否定位
function getLocationAuth() {
  // #ifdef APP-PLUS
  let system = uni.getSystemInfoSync() // 获取系统信息
  if (system.platform === 'android') { // 判断平台
    handleLocation.android()
  } else if (system.platform === 'ios') {
    handleLocation.ios()
  }
  // #endif
}

export default getLocationAuth
